package com.lvyuely.web.module.controller.auth;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.lvyuely.web.module.util.Encript;

@Controller
@RequestMapping("/auth")
public class LoginController {

	private final static Logger logger = Logger.getLogger(LoginController.class);
	@Autowired
	private DefaultWebSecurityManager securityManager;

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(Model model) {
		return "auth/login/login.ftl";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
		// 密码校验
		password = Encript.md5(username + Encript.md5(password));
		// 创建验证Token
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		SecurityUtils.setSecurityManager(securityManager);
		Subject subject = SecurityUtils.getSubject();
		try {
			// 验证登录
			subject.login(token);
			System.out.println(JSON.toJSONString(subject.getPrincipal()));
			return "redirect:/index";
		} catch (Throwable t) {
			model.addAttribute("error", t.getMessage());
		}
		model.addAttribute("username",username);
		model.addAttribute("password",password);
		return login(model);
	}

}
